import {
  createSlice,
  createAsyncThunk
} from '@reduxjs/toolkit'

export const whenOddIncreaseAction = createAsyncThunk('whenOddIncrease', async (data, store) => {
  const {
    count
  } = store.getState().count
  const result = await new Promise((resolve, reject) => {
    if (count % 2 !== 0) {
      resolve(data)
    }
    reject()
  })
  return result
})

// 防抖（简易版）
let timer = null
export const delayIncreaseAction = createAsyncThunk('delayIncrease', async (data) => {
  const result = await new Promise((resolve, reject) => {
    try {
      clearTimeout(timer)
      timer = setTimeout(() => {
        resolve(data)
      }, 2000)
    } catch (error) {
      reject()
    }
  })
  return result
})

const countSlice = createSlice({
  // 命名空间（type 前缀）
  name: 'count',
  // reducer 初始值
  initialState: {
    count: 0
  },
  // reducers
  reducers: {
    increase(state, {
      payload
    }) {
      // react-toolkit 中的 immt 包帮我们处理了数据覆盖
      state.count += payload
    },
    decrease(state, {
      payload
    }) {
      state.count -= payload
    }
  },
  extraReducers: {
    // whenOddIncrease/fulfilled
    [whenOddIncreaseAction.fulfilled](state, {
      payload
    }) {
      state.count += payload
    },
    [delayIncreaseAction.fulfilled](state, {
      payload
    }) {
      state.count += payload
    }
  }
})

// console.log(countSlice); // createSlice 会返回一个对象，包含 actions(对象包含异步操作), reducer(方法)

export default countSlice.reducer

// 模拟 createSlice 生成 reducer
/* function reducer(pevr=initialState, action) {
  const {type, data} = action
  switch (type) {
    case 'count/increase':
      return {
        
      };
    case 'whenOddIncrease/fulfilled':
      return {

      }
  }
} */

export const {
  increase,
  decrease
} = countSlice.actions